package com.s7.app.manager;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import java.io.File;

/**
 * Created by Administrator on 2017/5/23.
 * 版本信息工具
 */
public class VersionManager {

    private static   VersionManager versionManager;

    private VersionManager(){}

    public static VersionManager getInstance(){
        if (versionManager == null){
            versionManager = new VersionManager();
        }
        return versionManager;
    }

    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public Bundle getVersion(Context context){
        Bundle bundle = null;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            int versionCode = info.versionCode;
            if (bundle == null){
                bundle = new Bundle();
            }
            bundle.putString("versionName", version );
            bundle.putInt("versionCode",versionCode);
            return bundle;
        } catch (Exception e) {
            e.printStackTrace();
            return bundle;
        }
    }

    /**
     * 获取版本号
     * @return 当前应用的版本名
     */
    public String getVersionName(Context context){
        String versionName = null;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionName = info.versionName;
            return versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return versionName;
        }
    }

    /**
     * 获取版本号
     * @return 当前应用的版本号/版本名
     */
    public int getVersionCode(Context context){
        int versionCode = 0;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode;
            return versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return versionCode;
        }
    }

    /**
     * 安装apk_传入的是apk的路径
     * @param apkAbsolutePath
     * @param context
     */
    private void installApk(String apkAbsolutePath, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(apkAbsolutePath)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
